﻿using ApplicationModels.A02.Identities;
using ApplicationService;
using Commons.Enums;
using Commons.Helpers;
using Commons.Requests;
using Commons.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace WebAPI.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    [AllowAnonymous]
    public class AuthenticationController : ControllerBase
    {
        private readonly AuthenticationService service;
        public AuthenticationController(AuthenticationService service)
        {
            this.service = service;
        }
        [HttpPost]
        public async Task<MessageResponse> RegisterByAdmin(AccountAndPassword aap)
        {
            return await service.RegisterByAccount(aap.UserName,aap.Password,"role");
        }
        [HttpPost]
        public async Task<MessageResponse> LoginByAccount(AccountAndPassword aap)
        {
            return await service.LoginByAccountAsync(aap.UserName, aap.Password);
        }
        /// <summary>
        /// 微信登录
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SignResponse> LoginByWeChatAsync(LoginByWeChat lbw)
        {
            return await service.LoginByWeChatOpenIdAsync(lbw.Code);
        }
        /// <summary>
        /// 注册并登录
        /// </summary>
        /// <param name="lbw"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SignResponse> RegisterAndLoginByWeChatAsync(LoginByWeChat lbw)
        {
            return await service.RegisterAndLoginByWechatAsync(lbw);
        }


        /// <summary>
        /// 邮箱密码登录
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SignResponse> LoginByEmailAndPassword(LoginByEmaiAndPassword req)
        {
            return await service.LoginByEmailAsync(req.Email, req.Password);
        }

        /// <summary>
        /// 邮箱注册
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageResponse> RegisterByEmailAsync(RegisterByEmail req)
        {
            if ((await CheckByEmailAsync(req.Email)).Successed)
            {
                return new MessageResponse(400, "邮箱已存在!", false);
            }
            var redis = new RedisHelper();
            var code = await redis.StringGetAsync(req.Email);
            if (code == req.Code)
            {
                redis.KeyDelete(req.Email);
                return await service.RegisterByEmailAsync(req.Email, req.Password);
            }
            return new MessageResponse(400, "验证码错误", false);

        }

        [HttpPost]
        public async Task<SignResponse> RegisterByEmailAndCodeAsync(RegisterByEmail req)
        {
            var redis = new RedisHelper();
            var redisKey = "register_" + req.Email;
            var code = await redis.StringGetAsync(redisKey);
            if (code == req.Code)
            {
                redis.KeyDelete(redisKey);
                if ((await CheckByEmailAsync(req.Email)).Successed)
                {
                    return await service.LoginByEmailAndCodeAsync(req.Email);
                }
                TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var pwd = Convert.ToInt64(ts.TotalSeconds).ToString();
                var res = await service.RegisterByEmailAsync(req.Email, pwd);
                if (res.Successed)
                {
                    return await service.LoginByEmailAndCodeAsync(req.Email);
                }
                return new SignResponse("登录失败咯!", false);
            }
            return new SignResponse( "验证码错误!", false);
            
        }
        /// <summary>
        /// 测试账号注册接口
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task <MessageResponse> RegisterByAccount(AccountAndPassword account)
        {
            return await service.RegisterByAccount(account.UserName, account.Password, "user");
        }

        /// <summary>
        /// 发送邮箱验证码
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageResponse> SendEmailAsync(string email)
        {
            return await service.EmailSendAsync(email,EmailCodeTypeEnum.Regisger);
        }
        /// <summary>
        /// 发送修改密码的邮箱验证码
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageResponse> SendEmailByPasswordChangeAsync(string email)
        {
            return await service.EmailSendAsync(email, EmailCodeTypeEnum.Password);
        }
        /// <summary>
        /// 验证邮箱是否存在存在即Fail否则Success
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<SingleResponse> CheckByEmailAsync(string email)
        {
            return await CheckContainByEmailAsync(email);
        }


        private async Task<SingleResponse> CheckContainByEmailAsync(string email)
        {
            if (await service.FindUserByEmailAsync(email) != null)
            {
                return new SingleResponse();
            }
            else
            {
                return new SingleResponse(false);
            }
        }
        /// <summary>
        /// 邮箱验证码修改密码
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageResponse> ChangePasswordAsync(PasswordChange req)
        {
            var redis = new RedisHelper();
            var redisKey = "password_"+req.Email;
            var code = await redis.StringGetAsync(redisKey);
            if (code == req.Code)
            {
                if ((await CheckByEmailAsync(req.Email)).Successed)
                {
                    var res = await service.ChangePasswordByEmailCode(req.Email, req.Password);
                    if (res.Succeeded)
                    {
                        redis.KeyDelete(redisKey);
                        return new MessageResponse("修改成功!");
                    }

                    return new MessageResponse("修改失败!", false);
                }
                
                
            }
            return new SignResponse("验证码错误!", false);
        }




    }
}
